const express = require("express");
const multer = require("multer");
const path = require("path");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const cors = require("cors");
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
const { expressjwt: jwt } = require("express-jwt");
const SECRET_KEY = "login2023";

const indexRouter = require("./routes/index");
const loginRouter = require("./routes/login");
const adminRouter = require("./routes/admin");
const likeRouter = require("./routes/like");
const collectRouter = require("./routes/collect");
const commentRouter = require("./routes/comment");
const articleRouter = require("./routes/article");
const personalRouter = require("./routes/personal");
const { log } = require("console");

const app = express();

// 中间件
app.use(express.static("./public"));
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(cors());
app.use(
  jwt({
    secret: SECRET_KEY,
    algorithms: ["HS256"],
  }).unless({ path: ["/", /^\/api\//] }) // 设置白名单: api开头的请求不需要校验
);
app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.status(401).send("无权限, 请重新登录！");
  }
});

// 接口
app.use("/", indexRouter);
app.use("/admin", adminRouter);
app.use("/api", loginRouter);
app.use("/like", likeRouter);
app.use("/collect", collectRouter);
app.use("/comment", commentRouter);
app.use("/article", articleRouter);
app.use("/personal", personalRouter);

module.exports = app;
